#pragma once
#include <iostream>
#include "utility/index.hpp"
#include "request_access/index.hpp"
#include "data_access/index.hpp"
#include "components/index.hpp"

using namespace std;
using namespace utility;

namespace components2 {
    class ViewProduceOrder : public components::EntityRequest {
    public:
        COMPONENT_INSTANCE_FUNCTION(ViewProduceOrder);

        ViewProduceOrder();

        any Select2();
    private:
        vector<EntityData> getProductCompleteStatus(const vector<string> &idList);
    };

    ViewProduceOrder::ViewProduceOrder() {
        SET_METHOD_ACTION(Select2);
    }

    vector<EntityData> ViewProduceOrder::getProductCompleteStatus(const vector<string> &idList) {
        auto ids = "'" + EntityData::VectorToString(idList, "','") + "'";
        auto query = make_shared<data_access::Query>("v_SaleCompleteOrder_Detail");
        query->Select("SaleOrderId,count(*) RowCount");
        query->Where(Format("where SaleOrderId in ({0}) and BalanceNum<>0", ids), nullptr);
        query->GroupBy("group by SaleOrderId");

        return SelectEntities(query);
    }

    any ViewProduceOrder::Select2() {
        auto obj = any_cast<EntityData>(Select());
        auto list = obj.GetEntityDataList("Data");

        vector<string> idList;
        for (const auto& item :list) {
            auto status = item.GetInt("Status");
            if (status == 3) idList.emplace_back(item.GetString("SaleOrderId"));
        }

        auto completeStatusList = getProductCompleteStatus(idList);

        for (auto& item :list) {
            auto status = item.GetInt("Status");
            if (status == 3) {
                for (const auto &s: completeStatusList) {
                    if (item.GetString("SaleOrderId") == s.GetString("SaleOrderId")) {
                        item["CompleteStatus"]=1;
                        break;
                    }
                }
            }
        }

        obj["Data"]= list;

        return obj;
    }
}